package com.wrupple.vegetate.server.catalog.dao;

import javax.jdo.PersistenceManager;

import org.springframework.beans.factory.annotation.Autowired;

import com.wrupple.muba.common.server.bussiness.session.UserSessionInformationProvider;
import com.wrupple.vegetate.domain.FileWrapper;
import com.wrupple.vegetate.domain.PersistentFile;
import com.wrupple.vegetate.server.bussiness.PMF;
import com.wrupple.vegetate.server.dao.CatalogFileDAO;

public class JDOCatalogFileDAO implements CatalogFileDAO {

	@Autowired
	private UserSessionInformationProvider userSessionInformationProvider;

	@Override
	public String saveFile(byte[] file) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String regreso = null;
		Long domain = userSessionInformationProvider == null ? null : userSessionInformationProvider.getUserDomain();
		domain = domain == null ? 0 : domain;
		PersistentFile arc = new PersistentFile(domain);

		FileWrapper persistent = new FileWrapper();

		persistent.setContent(file);

		arc.setFileWithThumbnail(persistent);

		pm.makePersistent(arc);

		regreso = String.valueOf(arc.getId());

		return regreso;
	}

	public void setUserSessionInformationProvider(UserSessionInformationProvider userSessionInformationProvider) {
		this.userSessionInformationProvider = userSessionInformationProvider;
	}

	public UserSessionInformationProvider getUserSessionInformationProvider() {
		return userSessionInformationProvider;
	}

	@Override
	public byte[] loadFile(String fileId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		PersistentFile regreso = null;
		try {
			regreso = pm.getObjectById(PersistentFile.class, Long.parseLong(fileId));
		} catch (Exception e) {
			regreso = null;
		}
		return regreso.getFileWrapper().getContent();
	}

}
